package com.jiyinit.web.core.mobile.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.web.core.business.dao.TabLoginUserDao;
import com.jiyinit.web.core.business.entity.TabLoginInfoEntity;
import com.jiyinit.web.core.business.service.LoginInfoServiceImpl;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.vo.LoginResponseUserVo;
import com.jiyinit.web.core.business.vo.RedisUserVo;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.token.Token;
import com.jiyinit.web.core.common.util.Md5;
import com.jiyinit.web.core.common.util.MessagePush;
import com.jiyinit.web.core.common.vo.DeviceInfo;
import com.jiyinit.web.core.common.vo.LoginUserVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lishaochuan
 * @version 1.0
 * @date 2017/4/10 18:00
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/mlogin")
public class MloginController {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MloginController.class);

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "login.loginInfoServiceImpl")
    private LoginInfoServiceImpl loginInfoService;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    /**
     * 退出登录
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/mlogout")
    public ResponseEntity<ResponseDto> userLogout(HttpServletRequest request) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        TabCoreUserEntity tabCoreUserEntity = (TabCoreUserEntity)JsonEntityTransform.json2Object(logJson, TabCoreUserEntity.class);
        //已经登录的删除登录信息
        loginInfoService.delete(tabCoreUserEntity.getUserId());
        return new ResponseEntity<>(ResponseDto.responseOK("成功退出！"), HttpStatus.OK);
    }

    /**
     * 跳转错误页面
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value = "/error")
    public String redirectError(HttpServletRequest request) {
        request.getSession().invalidate();
        return "error/error";
    }

    /**
     * 跳转未授权页面
     * @author lishaochuan
     * @create 2017/4/11 12:27
     * @param
     * @return
     */
    @RequestMapping(value="/noAuthority")
    public String redirect403Error(HttpServletRequest request){
        return "error/403";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/mlogin")
    public ResponseEntity<ResponseDto> logintest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	TabCoreUserEntity tabCoreUserEntity = (TabCoreUserEntity)JsonEntityTransform.json2Object(logJson, TabCoreUserEntity.class);
        //过滤、转码%字符
        String filterPassWord=URLDecoder.decode(tabCoreUserEntity.getPassword().replaceAll("%", "%25"));
        tabCoreUserEntity.setPassword(filterPassWord);
        LoginUserVo loginUserVo = (LoginUserVo)JsonEntityTransform.json2Object(logJson, LoginUserVo.class);

        if (tabCoreUserEntity.getLoginName() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("登录名不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getPassword() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("密码不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getDeviceId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("设备ID不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getDeviceType() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("客户端类型不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getAppVersion() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("App版本不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getDeviceInfo() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("设备信息不能为空"), HttpStatus.OK);
        }
        if (tabCoreUserEntity.getIp() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("IP不能为空"), HttpStatus.OK);
        }
    	
    	String loginName = tabCoreUserEntity.getLoginName();
    	String password = tabCoreUserEntity.getPassword();
    	
        LogUtil.info(LOGGER, "loginName:{},password:{}", loginName,password);
        TabCoreUserEntity tabCoreUser = userService.login(loginName, password);
        HttpSession session = request.getSession();
        if(!Check.isNullObj(tabCoreUser)){
            UserUtil.setUser2Session(new CurrentUserVo(tabCoreUser));
            // 设置token
            RedisUserVo userVo = new RedisUserVo();
            userVo.setId(tabCoreUser.getUserId());
            userVo.setLoginName(tabCoreUser.getLoginName());
            userVo.setRealName(tabCoreUser.getUserName());
            userVo.setDeviceType(tabCoreUserEntity.getDeviceType().toString());
//            String token = RedisUtil.loginSetToken(redisOperate, tabCoreUserEntity.getDeviceType().toString(), userVo);

            //查看用户是否已经登录
            TabLoginInfoEntity loginInfo =  loginInfoService.getInfoByUserId(tabCoreUser.getUserId());
            String oldToken=loginInfo!=null?loginInfo.getToken():null;
            String token = Token.createToken(tabCoreUser);
            tabCoreUser.setToken(token);
            if(loginInfo == null){
                //没有登录增加信息
                TabLoginInfoEntity info = new TabLoginInfoEntity();
                info.setUserId(tabCoreUser.getUserId());
                info.setToken(token);
                info.setIsDelete(0);
                info.setMobileDesc(loginUserVo.getMobileDesc());
                info.setLastLoginTime(new Date());
                info.setCreateId(tabCoreUser.getUserId());
                info.setCreateTime(new Date());
                info.setChannel(loginUserVo.getChannel());
                loginInfoService.insert(info);
            }else{
                //登录修改信息
                loginInfo.setToken(token);
                loginInfo.setMobileDesc(loginUserVo.getMobileDesc());
                loginInfo.setLastLoginTime(new Date());
                loginInfo.setChannel(loginUserVo.getChannel());
                loginInfoService.update(loginInfo);
            }

            // 设置sign
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setAppVersion(tabCoreUserEntity.getAppVersion());
            deviceInfo.setDeviceId(tabCoreUserEntity.getDeviceId());
            deviceInfo.setDeviceInfo(tabCoreUserEntity.getDeviceInfo());
            deviceInfo.setDeviceType(tabCoreUserEntity.getDeviceType());

            String newSign = Md5.getDeviceSign(token, deviceInfo);
            LoginResponseUserVo responsevo = new LoginResponseUserVo();
            BeanUtils.copyProperties(tabCoreUser,responsevo);
            int topOrgId = orgService.getTopParentOrgId(tabCoreUser.getOrgId());
            responsevo.setTopOrgId(topOrgId);
            responsevo.setTopOrgName(orgService.selectById(topOrgId).getOrgName());
            responsevo.setNewSign(newSign);

            if(!Check.isNullStr(responsevo.getAvatar()))
            {
                String picPath = (String) PropertyPlaceholderConfigurer.getContextProperty("USER_AVATAR");
                responsevo.setAvatar(picPath+responsevo.getAvatar());
            }
            else
            {
                responsevo.setAvatar("");
            }

            //如果之前有已登录设备，则发送极光通知，app接到通知后，将之前设备上登录的账号登出
            //解决多个设备接收极光通知的问题
            if(loginInfo!=null&&newSign!=null&&!newSign.equals(loginInfo.getToken()))
            {
                String[] users=new String[]{String.valueOf(loginInfo.getUserId())};
                Map<String,String> resultMap=new HashMap<String,String>();
                resultMap.put("token",oldToken);
                resultMap.put("content","已在其它的设备登录");
                if(tabCoreUserEntity.getChannel()!=null&&tabCoreUserEntity.getChannel().equals("01")){
                    MessagePush messagePush = new MessagePush(users, JSONObject.toJSONString(resultMap));
                }else{
                    MessagePush messagePush = new MessagePush(users,JSONObject.toJSONString(resultMap));
                }
            }
            if(Check.isNullStrStrict(responsevo.getUserGroupNo())){
                responsevo.setUserGroupNo("");
            }
            if(Check.isNullStrStrict(responsevo.getUserAddress())){
                responsevo.setUserAddress("");
            }
            if(Check.isNullStrStrict(responsevo.getUserEmail())){
                responsevo.setUserEmail("");
            }

            return new ResponseEntity<>(ResponseDto.responseOK(responsevo), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("用户名或密码错误"), HttpStatus.OK);
    }

}
